package cn.com.open.itembank.controller;

import cn.com.open.itembank.common.GlobalConst;
import cn.com.open.itembank.dto.*;
import cn.com.open.itembank.entity.CourseItemBank;
import cn.com.open.itembank.interceptor.Log;
import cn.com.open.itembank.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by lucky on 2017/7/13.
 */

/**
 * 题库控制器
 */
@RestController
@RequestMapping("/itembank")
public class ItemBankController extends BaseController {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ItemBankController.class);

    @Autowired
    private ItemBankRemoteService itemBankService;

    //region 新增相关（Create：理论方法 HttpPost）

    //region 新增题库

    /**
     * 新增题库
     *
     * @param request  the request
     * @param response the response
     * @param model    the model
     */
    @Log(optType = "新增题库", optDescription = "新增题库，参数：%s", keyName = "model")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public void createItemBankForOuter(HttpServletRequest request, HttpServletResponse response,
                                       @RequestBody ItemBank model) {

        if (!isPermissionForAppId(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        ReturnModel result = itemBankService.insert(model, false);

        if (result.getCode() == GlobalConst.COURSE_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }
    }

    //endregion

    //region 新增题库(内部)

    /**
     * 新增题库(内部)
     *
     * @param request  the request
     * @param response the response
     * @param model    the model
     */
    @Log(optType = "新增题库(内部)", optDescription = "新增题库(内部)，参数：%s", keyName = "model")
    @RequestMapping(method = RequestMethod.POST)
    public void createItemBankForInner(HttpServletRequest request, HttpServletResponse response,
                                       @RequestBody ItemBank model) {

        if (!isPermissionForAppId(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //调用服务层方法
        ReturnModel result = itemBankService.insert(model, true);

        if (result.getCode() == GlobalConst.COURSE_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, result, "");
        }
    }

    //endregion

    //endregion

    //region 删除相关（Delete：理论方法 HttpDelete）

    //region 删除题库

    /**
     * 删除题库
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     */
    @Log(optType = "删除题库", optDescription = "删除题库，ID：%s", keyName = "itembankId")
    @RequestMapping(value = "/{itembankId}", method = RequestMethod.DELETE)
    public void deleteItemBank(HttpServletRequest request, HttpServletResponse response,
                               @PathVariable(value = "itembankId") String itembankId) {

        if (!isPermissionForAppId(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        if (!isPermissionForItemBank(request, itembankId)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        String appkey = request.getHeader(appKeyString);
        int result = itemBankService.delete(itembankId, appkey);

        if (GlobalConst.COURSE_NOT_EXIST == result) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result == GlobalConst.DATA_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else if (result == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }

    //endregion

    //endregion

    //region 更新相关（Update：理论方法 HttpPut）

    //region 修改题库

    /**
     * 修改题库
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     * @param courseName 课程题库名称
     */
    @Log(optType = "修改题库", optDescription = "修改题库，ID：%s", keyName = "itembankId")
    @RequestMapping(value = "/{itembankId}", method = RequestMethod.PUT)
    public void updateItemBank(HttpServletRequest request, HttpServletResponse response,
                               @PathVariable(value = "itembankId") String itembankId,
                               @RequestParam("courseName") String courseName) {

        int result = itemBankService.update(itembankId, courseName);

        if (result == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result == GlobalConst.COURSE_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, "", "", result);
        }
    }

    //endregion

    //region 修改题库状态

    /**
     * 修改题库状态
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     */
    @Log(optType = "修改题库状态", optDescription = "修改题库状态，ID：%s", keyName = "itembankId")
    @RequestMapping(value = "/{itembankId}/status", method = RequestMethod.PUT)
    public void updateItemBankStatus(HttpServletRequest request, HttpServletResponse response,
                                     @PathVariable(value = "itembankId") String itembankId) {

        int result = itemBankService.changeStatus(itembankId);

        if (result == GlobalConst.COURSE_NOT_EXIST || result == GlobalConst.INCOMPLETE_DATA) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            responseJson(request, response, "", "", result);
        }
    }

    //endregion

    //endregion

    //region 查询相关（Retrieve：理论方法 HttpGet）

    //region 获取题库信息

    /**
     * 获取题库信息
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     */
    @Log(optType = "获取题库信息", optDescription = "获取题库信息，ID：%s", keyName = "itembankId")
    @RequestMapping(value = "/{itembankId}", method = RequestMethod.GET)
    public void getItemBankInfo(HttpServletRequest request, HttpServletResponse response,
                                @PathVariable(value = "itembankId") String itembankId) {

        if (!isPermissionForItemBank(request, itembankId)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        CourseItemBank model = itemBankService.getCourseItemBankInfo(itembankId);
        if (model != null) {
            responseJson(request, response, model, "");
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    //endregion

    //region 下载文件 TODO：这个接口应该不存在，需要合并到导出试卷和导出试题接口中

    /**
     * 下载文件
     */
    @Log(optType = "下载文件", optDescription = "下载文件，地址：%s", keyName = "fileName")
    @GetMapping(value = "/download")
    public byte[] downLoad(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam("fileName") String fileName) throws IOException{
        InputStream inputStream = null;
        try {
            File file = new File(fileName);
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            byte[] buf = new byte[1024];
            OutputStream out = response.getOutputStream();
            inputStream = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = inputStream.read(buf)) != -1) {
                out.write(buf);
            }
            inputStream.close();
            out.flush();
            out.close();
        } catch (IOException e1) {
            logger.error(e1);
        } finally {
            inputStream.close();
        }
        return null;
    }

    //endregion

    //endregion
}